package com.example.jdai.jdai.util;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.example.jdai.jdai.MyApplication;
import com.example.jdai.jdai.R;
import com.example.jdai.jdai.config.Config;
import com.example.jdai.jdai.rest.Contact;
import com.example.jdai.jdai.rest.GetData;
import com.example.jdai.jdai.rest.RestApi;
import com.example.jdai.jdai.rest.SendCode;
import com.example.jdai.jdai.rest.bean.LoginBean;
import com.example.jdai.jdai.rest.bean.Verify_info;
import com.example.jdai.jdai.threeparty.UpdataService;
import com.example.jdai.jdai.ui.LoginActivity;
import com.example.jdai.jdai.ui.MainActivity;
import com.example.jdai.jdai.ui.ScActivity;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import retrofit2.Response;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by hellopyj on 2017/1/9.
 */

public class Tools {
    //获得全部联系人
    public static boolean GetContacts() {
        try {
        ArrayList<Contact> contacts=new ArrayList<>();
        ContentResolver cr = MyApplication.applicationContext.getContentResolver();
        //long timeStart = new Date().getTime();
        String[] mContactsProjection = new String[]{
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts.PHOTO_ID
        };
        Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, mContactsProjection, null, null, null);
        //String contactsId;
        String phoneNum;
        String name;
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                // contactsId = cursor.getString(0);
                phoneNum = cursor.getString(1);
                name = cursor.getString(2);
                contacts.add(new Contact(name,phoneNum));

            }
            cursor.close();
        }
        if(contacts.size()==0){
           return false;
        }
       // Log.v("hhh",new GsonBuilder().setPrettyPrinting().create().toJson(contacts));

       // RestApi.AddService service = MyApplication.retrofit.create(RestApi.AddService.class);
        SendCode send=new SendCode ();
        send.data.put("user_id",MyApplication.dataAll.data.get(DataAll.LOGIN_ID));
        send.data.put("contacts",MyApplication.gson.toJson(contacts));

        Call call =MyApplication.okClient.newCall(Tools.getRequest(Config.CONNECT_ADD_URL,send));
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                if (Config.ISDEBUG)
                    Log.v("connect_add",response.body().string());
            }

        });
        return true;}
        catch (Exception e){
            if(Config.ISDEBUG){
                Log.v("contect",e.toString());
            }
            return false;
        }

    }
    //通过url获得pic
    public static String getPicByUri(Uri selectedImage) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = MyApplication.applicationContext.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(MyApplication.applicationContext, "find_img", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return"";
            }
            return picturePath;
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(MyApplication.applicationContext, "find_img", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return "";

            }
            return file.getAbsolutePath();
        }

    }
//    手持进入
    public static boolean firstIn()
    {
        return MyApplication.applicationContext.getSharedPreferences(Config.SP_NAME, Context.MODE_PRIVATE).getBoolean(DataAll.FIRST_IN,true);
    }
    //    是否登入
    public static String hasLogin()
    {
        return MyApplication.dataAll.data.get(DataAll.HAS_LOGIN);
    }
    //图片是否存在判定
    public static boolean isPicHas(String src) {
        if ("".equals(src))
            return false;
        File file = new File(src);
        if (!file.exists())
            return false;
        return true;
    }
//    获得版本号
    public static int  getVersionCode(){
        PackageManager manager = MyApplication.applicationContext.getPackageManager();//获取包管理器
        try {
            //通过当前的包名获取包的信息
            PackageInfo info = manager.getPackageInfo(MyApplication.applicationContext.getPackageName(),0);//获取包对象信息
            return  info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取坂本明
     * @return
     */
    public static String getVersionName(){
        PackageManager manager = MyApplication.applicationContext.getPackageManager();
        try {
            //第二个参数代表额外的信息，例如获取当前应用中的所有的Activity
            PackageInfo packageInfo = manager.getPackageInfo(MyApplication.applicationContext.getPackageName(), PackageManager.GET_ACTIVITIES
            );
            ActivityInfo[] activities = packageInfo.activities;
            return packageInfo.versionName;
        } catch (Exception e) {
            //e.printStackTrace();
            Log.v("hello","pyj");
        }
        return "";
    }
    public static  String getConnectByUri(Uri uri)
    {
        String[] contact=new String[2];
//得到ContentResolver对象
        ContentResolver cr = MyApplication.applicationContext.getContentResolver();
//取得电话本中开始一项的光标
        Cursor cursor=cr.query(uri,null,null,null,null);
        if(cursor!=null)
        {
            cursor.moveToFirst();
//取得联系人姓名
            int nameFieldColumnIndex=cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0]=cursor.getString(nameFieldColumnIndex);
//取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if(phone != null){
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        }
        else
        {
            return null;
        }
        return contact[0]+":"+contact[1];
    }
    //md5
    public static String getMD5(String str) {
        str+=DataAll.HAS_LOGIN;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(32);
        } catch (Exception e) {
        }
        return "";
    }
    public static String getM5(String str){
        try{
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes("UTF-8"));    //问题主要出在这里，Java的字符串是unicode编码，不受源码文件的编码影响；而PHP的编码是和源码文件的编码一致，受源码编码影响。
            StringBuffer buf=new StringBuffer();
            for(byte b:md.digest()){
                buf.append(String.format("%02x", b&0xff));
            }
            return  buf.toString();
        }catch( Exception e ){
            e.printStackTrace();

            return null;
        }
    }
    //    更新
   public static void Update(final Context context)
    {
        //RestApi.UpdateService service = MyApplication.retrofit.create(RestApi.UpdateService.class);
        SendCode send=new SendCode();
        send.data.put("version",Tools.getVersionName());
        send.data.put("platform","2");
        Call call =MyApplication.okClient.newCall(Tools.getRequest(Config.UPDATE_URL,send));
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {

                int code=response.code();
                String bd=response.body().string();
                if (Config.ISDEBUG)
                    Log.v("update", bd);
                if(response.code()==200) {

                    final GetData<Map> getD=MyApplication.gson.fromJson(bd,new TypeToken<GetData<Map>>(){}.getType());
                    if(!MyApplication.dataAll.data.get(DataAll.VERSION).equals((String)getD.getData().get("version"))) {
                        //LoganSquare.parse(response.body().toString(),GetData.class);
                        String tip = (String) getD.getData().get("summary");
                        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        //    设置Title的图标
                        builder.setIcon(R.drawable.logo1);
                        builder.setTitle("升级提示");
                        if (tip == "")
                            tip = "有新版本!是否要升级？";
                        builder.setMessage(tip);
                        //    设置一个PositiveButton
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String name = (String) getD.getData().get("version");
                                File file = new File(name + ".apk");
                                if (!file.exists()) {
                                    Intent intent = new Intent(MyApplication.applicationContext, UpdataService.class);
                                    intent.putExtra("url", (String) getD.getData().get("file"));
                                    intent.putExtra("name", name);
                                    context.startService(intent);
                                }
                            }
                        }).setNegativeButton("忽略", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                MyApplication.dataAll.data.put(DataAll.VERSION, (String) getD.getData().get("version"));
                                MyApplication.dataAll.saveAll();

                            }
                        });
                        Tools.postToMain(new Runnable() {
                            @Override
                            public void run() {
                                builder.show();
                            }
                        });

                    }
                }

            }

        });

    }
    //发送到主线程
    public static void postToMain(Runnable r) {
        android.os.Handler h = new android.os.Handler(Looper.getMainLooper());
        h.post(r);
    }
    //获得RequestBody
    public static Request getRequest(String url,SendCode sd){
        RequestBody req= null;
        req = RequestBody.create(MediaType.parse("application/json"), sd==null?"":MyApplication.gson.toJson(sd));
        if(Config.ISDEBUG) {
            if(sd!=null)
            Log.v("json", MyApplication.gson.toJson(sd));
        }
        Request request = new Request.Builder()
                .url(url)
                .post(req)
                .header("App-Version",getVersionCode()+"")
                .header("X-Token",MyApplication.sp.getString("token","0"))
                .build();
        return  request;
    }
//保存
    public static void saveData(Verify_info vi){
        //info
        DataAll.dataLnfo.data.put(DataLnfo.ID_NUM,vi.getId_num());
        DataAll.dataLnfo.data.put(DataLnfo.ID_FRONT,vi.getId_photo_front());
        DataAll.dataLnfo.data.put(DataLnfo.ID_H_FRONT,vi.getId_photo_person_front());
        DataAll.dataLnfo.data.put(DataLnfo.ID_BEHIND,vi.getId_photo_back());
        DataAll.dataLnfo.data.put(DataLnfo.ID_H_BEHIND,vi.getId_photo_person_back());
        DataAll.dataLnfo.data.put(DataLnfo.STUDY,vi.getDegree());
        DataAll.dataLnfo.data.put(DataLnfo.NAME,vi.getName());
        DataAll.dataLnfo.data.put(DataLnfo.QQ,vi.getQq());
        DataAll.dataLnfo.data.put(DataLnfo.ADDRESS_J,vi.getAddress_detail());
        DataAll.dataLnfo.data.put(DataLnfo.INFO_STATUS,vi.getPerson_verify());
        //phone
        DataAll.dataPhone.data.put(DataPhone.PHONE_NUM,vi.getTel());
        DataAll.dataPhone.data.put(DataPhone.PHONE_CODE,vi.getTel_verify());

//        DataAll.dataLnfo.data.put(DataLnfo.a,vi.getId_num());
//        DataAll.dataLnfo.data.put(DataLnfo.ID_NUM,vi.getId_num());
//        DataAll.dataLnfo.data.put(DataLnfo.ID_NUM,vi.getId_num());
//        DataAll.dataLnfo.data.put(DataLnfo.ID_NUM,vi.getId_num());
        //contect
        DataAll.dataConnect.data.put(DataConnect.CT_TO,vi.getContact1_relation());
        DataAll.dataConnect.data.put(DataConnect.CT_OTHER,vi.getContact2_relation());
        if(!TextUtils.isEmpty(vi.getContact1_tel()))
        DataAll.dataConnect.data.put(DataConnect.CT_TO_TEL,vi.getContact1_name()+":"+vi.getContact1_tel());
        if(!TextUtils.isEmpty(vi.getContact2_tel()))
        DataAll.dataConnect.data.put(DataConnect.CT_OTHER_TEL,vi.getContact2_name()+":"+vi.getContact2_tel());
        DataAll.dataConnect.data.put(DataConnect.CT_STATUS,vi.getContact_verify());
        //zfb
        DataAll.dataZfb.data.put(DataZfb.ZFB_NAME,vi.getZfb_username());
        DataAll.dataZfb.data.put(DataZfb.ZFB_STATUS,vi.getZfb_verify());
        //jd
        DataAll.dataJd.data.put(DataJd.BT_NAME,vi.getJd_username());
        DataAll.dataJd.data.put(DataJd.BT_STATUS,vi.getJd_verify());
        //zx
        DataAll.dataZx.data.put(DataZx.ZX_NAME,vi.getZx_username());
        DataAll.dataZx.data.put(DataZx.ZX_STATUS,vi.getZx_verify());
        //zima
        MyApplication.dataAll.data.put(DataAll.ZIMA_STATUS,vi.getZmxy_verify());

    }
    //获得sdk
    public static int getTargetSdkVersion(){
        PackageManager manager = MyApplication.applicationContext.getPackageManager();//获取包管理器
        try {
            //通过当前的包名获取包的信息
            PackageInfo info = manager.getPackageInfo(MyApplication.applicationContext.getPackageName(),0);//获取包对象信息
            return  info.applicationInfo.targetSdkVersion;
        } catch (Exception e) {
            Log.v("hello","pyj");
            //e.printStackTrace();
        }
        return 0;
    }
    //权限检查
    public static boolean selfPermissionGranted(Context context,String permission) {
        // For Android < Android M, self permissions are always granted.
        boolean result = true;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (Tools.getTargetSdkVersion() >= Build.VERSION_CODES.M) {
                // targetSdkVersion >= Android M, we can
                // use Context#checkSelfPermission
                result = context.checkSelfPermission(permission)
                        == PackageManager.PERMISSION_GRANTED;
            } else {
                // targetSdkVersion < Android M, we have to use PermissionChecker
                result = PermissionChecker.checkSelfPermission(context, permission)
                        == PermissionChecker.PERMISSION_GRANTED;
            }
        }
        if(Config.ISDEBUG)
        {
            Log.v(permission,result?"ok":"on");
        }

        return result;
    }
    public static String saveMyBitmap(String bitName,Bitmap mBitmap){
        String externalStoragePath = Environment.getExternalStorageDirectory().getPath()+"/"+bitName + ".png";
        Log.v("sss",externalStoragePath);

        File f = new File(externalStoragePath );
        try {
            f.createNewFile();
            } catch (IOException e) {
            // TODO Auto-generated catch block
            }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
            } catch (Exception e) {
            e.printStackTrace();
            }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        try {
            fOut.flush();
            } catch (IOException e) {
            e.printStackTrace();
            }
        try {
            fOut.close();
            } catch (IOException e) {
            e.printStackTrace();
            }
        return externalStoragePath;
    }
    public  static void updataMedia(final Activity ac, String filePath) throws Exception{
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)//版本号的判断  4.4为分水岭，发送广播更新媒体库
        {
            MediaScannerConnection.scanFile(ac, new String[]{filePath}, null, new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    mediaScanIntent.setData(uri);
                    ac.sendBroadcast(mediaScanIntent);
                }
            });
        } else {
            ac.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(new File(filePath))));
        }

    }


}
